#!usr/bin/env python
# -*- coding:utf-8 -*-

import os
import random
import logging
import shutil
import string
import platform

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s : %(message)s',
                    datefmt='%Y-%m-%d %X', filename='./log/genTickets.log', filemode='w')
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s%(asctime)s - %(filename)s:%(lineno)s - %(message)s')
console.setFormatter(formatter)
#logging.getLogger('').addHandler(console)
# i = random.randint(0,len(StringType)-1)
'''
    大小写 ，缺少字母，多字母都是非法的;
    input--------String type;
    output-------String type;
'''
def is_Linux():
    return True if platform.system() == "Linux" else False

def is_Windows():
    return True if platform.system() == "Windows" else False

def cmp_lst(lst1, lst2, justOneEle=True, strictmode=True):
    if strictmode:
        if len(lst1) == 0 or len(lst2) == 0:
            return False
    if justOneEle:
        #列表交集
        return list(set(lst1).intersection(set(lst2))) and True or False
    else:
        return lst1 == lst2

#generate_invalid_vlue = lambda StringType, i: [lower_upper_alpha, del_insert_element][i % 2](StringType, i)
def generate_invalid_vlue(validString):
    i = random.randint(0, len(validString) - 1)
    invalidstr = lower_upper_alpha(validString, i)
    return invalidstr

def lower_upper_alpha(aString, i):
    logging.info("Start to lower or uppper or del a element.")
    if not isinstance(aString, basestring):
        logging.error("Unsupported type[%s] selected, please re-check." % type(aString))
        return aString
    aLst = list(aString)
    if aLst[i].islower():
        aLst[i] = aLst[i].upper()
    if aLst[i].isupper():
        aLst[i] = aLst[i].lower()
    if aLst[i].isdigit():
        aLst[i] = aLst[i] * 3  # HR12-->HR112
    else:
        del(aLst[i])  # zh-CN-->zhCN,' '-->''
    return ''.join(aLst)


def del_insert_element(aString, i):
    logging.info("Start to insert or del a element.")
    if not isinstance(aString, basestring):
        return
    func = [insert_element, del_element][i % 2]
    return func(list(aString), i)


def del_element(lst, i):
    if len(lst) == 0:
        return lst
    if not i in range(0, len(lst)):
        return lst
    logging.info("Del element, index is %s." % i)
    del lst[i]
    return ''.join(lst)


def insert_element(lst, i):
    if len(lst) == 0:
        return lst
    if not i in range(0, len(lst)):
        return lst
    logging.info("Insert element, index is %s." % i)
    lst.insert(i, lst[i])
    return ''.join(lst)


def getfilelist(dir, fileList):
    newDir = dir
    if os.path.isfile(dir):
        fileList.append(dir.decode('gbk'))
    elif os.path.isdir(dir):
        for s in os.listdir(dir):
            #如果需要忽略某些文件夹，使用以下代码
            #if s == "xxx":
                #continue
            newDir=os.path.join(dir,s)
            getfilelist(newDir, fileList)
    return fileList

def checkpath(ticketspath, capfolder, willmake=True):
    capticketspath = ticketspath +os.sep+capfolder
    if os.path.exists(capticketspath):
        logging.info("Ticket path already exist, remove it.")
        try:
            shutil.rmtree(capticketspath)
        except WindowsError as e:
            #use unlocker to kill process
            logging.error("Remove ticket path fail.")
            return False
    if willmake:
        logging.info("Will make a new dir of ticket path.")
        temppath = ticketspath + 'Temp'+ os.sep+ capfolder
        if os.path.isdir(temppath):
            shutil.copytree(temppath, capticketspath)
            return True
        else:
            logging.error("copy temppath [%s] fail " % temppath)
            return False
    return True

def gen_attr_values(thetp, lenstring, minnum, maxnum, stepnum, selected, deselected):
    '''
        to string element,will return 2 examples: one legal, another one illegal
    '''
    mydict = {}
    if thetp.lower() == "string":
        try:
            lenstring = int(lenstring)
            logging.info("Now we want a max lenth[%s] string." % lenstring)

            mystrFun = lambda x: ''.join(
                random.sample(string.ascii_letters * 2 + string.digits*2, x))
            mystrLst = map(mystrFun, [random.randint(0, lenstring), lenstring + 1])
            for mystr in mystrLst:
                if len(mystr) <= lenstring:
                    mydict[mystr] = "OK"
                else:
                    mydict[mystr] = "NOK"
            return {thetp:mydict}
        except ValueError as e:
            logging.error("Probaly param type error: %s" % str(e))

    if thetp.lower() in ["double", "integer", "int","nonnegativeinteger","positiveinteger"]:
        if thetp == "double":
            tp, ntp = float, int
        #---------------- 加入对"Int","Integer"类型的处理，使"Int","Integer"可以生成对应的tickets文件---------------------（chao yi 2017-4-7）
        if thetp in ["integer", "int","NonNegativeInteger","PositiveInteger","Int","Integer"]:
        #---------------- 加入对"Int","Integer"类型的处理，使"Int","Integer"可以生成对应的tickets文件---------------------（chao yi 2017-4-7）
            tp, ntp = int, float
        minnum, maxnum, stepnum = int(minnum), int(maxnum), tp(stepnum)
        inOknum = minnum + random.randint(0, (maxnum - minnum)/stepnum) * stepnum
        inNoknum = minnum + float(stepnum)/2
        outNoknum = maxnum + stepnum
        return {thetp: {inOknum:"OK", inNoknum:"NOK", outNoknum:"NOK" }}
    
    if thetp.lower() in ["enabledisable","boolean"]:
        in_vld = map(generate_invalid_vlue, [selected, deselected])
        return {thetp: {selected:"OK", deselected:"OK", in_vld[0]:"NOK", in_vld[1]:"NOK" }}
    
def gen_attr_enum(thetp,enum_Value):
    '''
        return dictionary of valid and invalid enum
    '''
    mydict = {}
    enableList = {'OK': ['disabled', 'enabled'], 'NOK': ['disable', 'enable', 'disabledd', 'enabledd']}
    daysOfWeekList ={'OK':['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],'NOK':['January','February','March','April','May','June','July','August','September','October','November','December']}
    duplexBindingOptionList = {'OK': ['longEdge', 'shortEdge'], 'NOK': ['long', 'short']}
    keyPressVolumeList ={'OK':['longEdge','shortEdge'],'NOK':['Large']}
    faxList ={'OK':['No','Yes'],'NOK':['off','on','true','false']}
    powerSave ={'OK':['off','on'],'NOK':['true','false']}
    if enum_Value == enableList['OK']:
        for valid in enableList['OK']:
            mydict[valid] = "OK"
        for invalid in enableList['NOK']:
            mydict[invalid] = "NOK"
    elif enum_Value == duplexBindingOptionList['OK']:
        for valid in duplexBindingOptionList['OK']:
            mydict[valid] = "OK"
        for invalid in duplexBindingOptionList['NOK']:
            mydict[invalid] = "NOK"
    elif enum_Value ==keyPressVolumeList['OK']:
        for valid in keyPressVolumeList['OK']:
            mydict[valid] = "OK"
        for invalid in keyPressVolumeList['NOK']:
            mydict[invalid] = "NOK"
    elif enum_Value == faxList['OK']:
        for valid in faxList['OK']:
            mydict[valid] = "OK"
        for invalid in faxList['NOK']:
            mydict[invalid] = "NOK"
    elif enum_Value == powerSave['OK']:
        for valid in powerSave['OK']:
            mydict[valid] = "OK"
        for invalid in powerSave['NOK']:
            mydict[invalid] = "NOK"
    elif enum_Value == daysOfWeekList['OK']:
        for valid in daysOfWeekList['OK']:
            mydict[valid] = "OK"
        for invalid in daysOfWeekList['NOK']:
            mydict[invalid] = "NOK"
    else:
        for valid in enum_Value:
            mydict[valid] = "OK"
        for valid in enum_Value:
            invalid = generate_invalid_vlue(valid)
            mydict[invalid] = "NOK"
    return {thetp: mydict}

def gen_enumattr_values(thetp,enum_Value):
    '''
        to string element,will return 2 examples: one legal, another one illegal
    '''
    mydict = {}
    if thetp.lower() == "enum":
        try:
            lenstring = int(enum_Value)
            logging.info("Now we want a max lenth[%s] string." % lenstring)

            mystrFun = lambda x: ''.join(
                random.sample(string.ascii_letters * 2 + string.digits*2, x))
            mystrLst = map(mystrFun, [random.randint(0, lenstring), lenstring + 1])
            for mystr in mystrLst:
                if len(mystr) <= lenstring:
                    mydict[mystr] = "OK"
                else:
                    mydict[mystr] = "NOK"
            return {thetp:mydict}
        except ValueError as e:
            logging.error("Probaly param type error: %s" % str(e))
        return mydict

def nmb_of(number_of_string_type):
    lenth = len(number_of_string_type)
    if lenth == 0: return number_of_string_type
    if lenth <= 3:
        return "Step"+ "0"*(3-lenth) + number_of_string_type
    return "Step" + number_of_string_type

if __name__ == '__main__':
    value = ["angola", "argentina", "australia"]
    print generate_invalid_vlue(value)
